﻿from django.db import models, backend
from django.db import connection 

class SearchQuerySet(models.query.QuerySet):
    def __init__(self, model=None, query=None,  fields=None):
        super(SearchQuerySet, self).__init__(model, query)
        self._search_fields = ('summary', 'description')#fields
        
    def search(self, q):
        meta = self.model._meta
        
        # Get the table name and column names from the model
        # in `table_name`.`column_name` style   meta.get_field(name, many_to_many=False).column
        columns = [name for name in self._search_fields]
        full_names = ["%s.%s" % (connection.ops.quote_name(meta.db_table), connection.ops.quote_name(column)) for column in columns]

        # Create the MATCh/AGAINST expressions        
        fulltext_columns = ", ".join(full_names)
        match_expr = ("MATCH(%s) AGAINST (%%s)" % fulltext_columns)
        
        # Add the extra SELECT and WHERE options
        return self.extra(select={'relevance': match_expr}, where=[match_expr], params=[q, q])
        #return super(SearchQuerySet, self).(self.extra(select={'relevance': match_expr}, where=[match_expr], params=[query]))


class SearchManager(models.Manager):
    def __init__(self, fields):
        super(SearchManager, self).__init__()
        self._search_fields = fields

    def get_query_set(self):
        return SearchQuerySet(self.model, None, self._search_fields)

    def search(self, query):
        return self.get_query_set().search(query)